(require* sketch/parse/rule/common/line)
(require* sketch/parse/rule/common/block)
(require* sketch/parse/rule/common/arrow)

(import sketch.shape.domain.*)
(import sketch.shape.domain.LinkEnd$TYPE)

(defrule linkend2-plain
    ""
	(declare (salience 60))
    ?fl <- (shape (name "Line") (obj ?l))
    ?f1 <- (shape (name "Rectangle") (obj ?r1))
    ?f2 <- (shape (name "Rectangle") (obj ?r2&~?r1))
    (test (call ShapePredicate onPointRectangle (?l getP1) ?r1))
    (test (call ShapePredicate onPointRectangle (?l getP2) ?r2))
    =>
    (printout "recognize linkend2 = line")

    (bind ?sh1 (new LinkEnd))
    (?sh1 setEndShape ?r1)
    (bind ?l1 (new Line (?l getP1) (?l getCenter)))
    (?sh1 setEnd ?l1)
    (bind ?v1 (?sh1 getPath))
    (?v1 add ?l1)
    (?sh1 setPath ?v1)

    (bind ?sh2 (new LinkEnd))
    (?sh2 setEndShape ?r2)
    (bind ?l2 (new Line (?l getP2) (?l getCenter)))
    (?sh2 setEnd ?l2)
    (bind ?v2 (?sh2 getPath))
    (?v2 add ?l2)
    (?sh2 setPath ?v2)

    (retract ?fl)
    (retract ?f1)
    (retract ?f2)

    (assert (shape
            (name "LinkEnd")
            (obj ?sh1)
            (children ?l)))
    (assert (shape
            (name "LinkEnd")
            (obj ?sh2)
            (children ?l)))

	(recognize ?sh1 (list-children (create$ ?l)))
    (recognize ?sh2 (list-children (create$ ?l))))

(defrule linkend-plain
    ""
    (declare (salience 50))
    ?fr <- (shape (name "Rectangle") (obj ?r))
    ?fl <- (shape (name "Line") (obj ?l))
	(test (call ShapePredicate connectsRectangleLine ?r ?l))
    =>
    (printout "recognize linkend = line")
    (bind ?sh (new LinkEnd))
    (?sh setEndShape ?r)
    (?sh setEnd ?l)
    (bind ?v (?sh getPath))
    (?v add ?l)
    (?sh setPath ?v)
    (?sh setType (LinkEnd$TYPE.PLAIN))
    (retract ?fr)
    (retract ?fl)
    (assert (shape
            (name "LinkEnd")
            (obj ?sh)
            (children ?l)))
    (recognize ?sh (list-children (create$ ?l))))
